package cn.chengpengper.seckill.stock.application.event.handler;

import cn.chengpengper.seckill.stock.application.cache.SeckillStockBucketCacheService;
import cn.chengpengper.seckill.stock.domain.event.SeckillStockBucketEvent;
import cn.chengpengper.seckill.stock.domain.model.enums.SeckillStockBucketEventType;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.event.EventHandler;
import com.alibaba.cola.event.EventHandlerI;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.util.Objects;

/**
 * @author chengpeng.hu
 */
@Slf4j
@EventHandler
@RequiredArgsConstructor
@ConditionalOnProperty(name = "message.mq.type", havingValue = "cola")
public class SeckillStockColaEventHandler implements EventHandlerI<Response, SeckillStockBucketEvent> {

    private final SeckillStockBucketCacheService seckillStockBucketCacheService;

    @Override
    public Response execute(SeckillStockBucketEvent seckillStockBucketEvent) {
        log.info("SeckillStockColaEventHandler|cola|接收库存事件|{}", JSON.toJSON(seckillStockBucketEvent));
        if(Objects.isNull(seckillStockBucketEvent) || Objects.isNull(seckillStockBucketEvent.getId())){
            log.info("SeckillStockColaEventHandler|cola|参数错误");
            return Response.buildSuccess();
        }
        //开启了库存分桶，就更新缓存数据
        if (SeckillStockBucketEventType.ENABLED.getCode().equals(seckillStockBucketEvent.getStatus())){
            seckillStockBucketCacheService.tryUpdateSeckillStockBucketCacheByLock(seckillStockBucketEvent.getId(), false);
        }
        return Response.buildSuccess();

    }
}
